import * as service from '../services/login';
import {routerRedux} from 'dva/router';//react-router-redux push
import {decode} from 'jsonwebtoken';
export default {
  namespace:'login',
  state:{
      isLogin:true,//是否登录
      errorInfo:'',//放着报错信息
      userInfo:null//如果用户登录之后，会把用户信息放在这里
  },
  effects:{
      *signup({payload},{call,put}){
        yield call(service.signup,payload);
      },
      *login({payload},{call,put}){
        let token = yield call(service.login,payload);
          localStorage.setItem('token',token);
          let userInfo = decode(token);
          yield put({type:'save',payload:{userInfo}});
          //如果登录成功的话，就跳转到 /admin路由里去
          yield put(routerRedux.push('/admin'));
      },
      *loadUserFromLocal({payload},{call,put}){
        let token = localStorage.getItem('token');
        let userInfo = decode(token);
        yield put({type:'save',payload:{userInfo}});
      }
  },
  reducers:{
    save(state,{payload}){ // {type:'save',payload:{isLogin:true}}
      return {...state,...payload}
    }
  }
}